package com.example.blank700.alarmservice;

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import java.util.Calendar;

public class AlarmServiceActivity extends AppCompatActivity implements OnClickListener {
    private static AlarmServiceActivity appRef=null;
    private Button b_call_service,b_exit_service;
    boolean k=false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        appRef=this;
        setContentView(R.layout.activity_alarm_service);

        b_call_service=(Button)findViewById(R.id.call_alarm_service);
        b_call_service.setOnClickListener(this);
        b_exit_service=(Button)findViewById(R.id.exit);
        b_exit_service.setOnClickListener(this);
    }

    public static AlarmServiceActivity getApp(){
        return appRef;
    }

    public void btEvent(String data){
        setTitle(data);
    }

    public void onClick(View arg0){
        if (arg0==b_call_service){
            setTitle("Waiting... Alarm=5");
            Intent intent=new Intent(AlarmServiceActivity.this,AlarmRecevier.class);
            PendingIntent pendingIntent=PendingIntent.getBroadcast(
                    AlarmServiceActivity.this,0,intent,0);
            //设置等待时间
            Calendar calendar=Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            calendar.add(Calendar.SECOND,3);
            //在规定的时间间隔到了后实现提醒服务
            AlarmManager alarmManager=(AlarmManager)getSystemService(ALARM_SERVICE);
            /*AlarmManager的set方法中，第一个参数是时钟类型，AlarmManager.RTC_WAKEUP是当系统进入
            睡眠状态时，也会唤醒系统；第二个参数是闹钟执行的时间；第三个参数是闹钟响应的动作。*/
            alarmManager.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),pendingIntent);
        }

        if (arg0==b_exit_service){
            Intent intent=new Intent(AlarmServiceActivity.this,AlarmRecevier.class);
            PendingIntent pendingIntent=PendingIntent.getBroadcast(
                    AlarmServiceActivity.this,0,intent,0);
            AlarmManager alarmManager=(AlarmManager)getSystemService(ALARM_SERVICE);
            alarmManager.cancel(pendingIntent);
            finish();
        }
    }
}
